import Vue from "vue"
import Router from "vue-router"
import { menu } from "@/utils"
import { mapGetters, mapMutations } from 'vuex'
import context from '@/main'
Vue.use(Router)

const { getMenu } = mapGetters(['getMenu'])
const { SET_NAVLIST, SET_ROUTERLIST } = mapMutations(['SET_NAVLIST', 'SET_ROUTERLIST'])

const router = new Router({
  mode: "history",
  base: `${process.env.VUE_APP_PUBLICPATH}`,
  routes: [
    {
      path: "/",
      redirect: "/login"
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/login")
    },
    {
      path: "/menu",
      name: "menu",
      component: () => import("@/views/menu/menu"),
      children: []
    }
  ]
})

// 设置顶部的层级路由
const setNavList = (idList) => {
  const partner = getMenu.apply(context).find(i => i.id == idList[0])
  const { path: childPath, title, children = [] } = partner
  let arr = []
  arr.push({
    path: childPath,
    title
  })
  idList.forEach((i, index) => {
    if (index) {
      arr.push(...getNavList(children, i))
    }
  })
  return arr
}
// 获取路由
const getNavList = (children, id) => {
  let result = []
  // 递归处理菜单数据
  for (let i = 0; i < children.length; i++) {
    const item = children[i]
    if (item.id == id) {
      result.push({
        path: item.path,
        title: item.title
      })
      break
    } else if (item.children) {
      result.push(...getNavList(item.children, id))
    }
  }
  return result
}

// 回到顶部
const goTop = () => {
  if (document.querySelector('.content')) {
    document.querySelector('.content').scrollTop = 0
  }
}

router.afterEach((to, from) => {
  // 设置导航路由标题和导航列表
  if (to.path.includes("menu") && Object.keys(to.meta).length) {
    const { path, meta: { idList, id, title } } = to
    SET_NAVLIST.apply(context, [setNavList([...idList, id])])
    SET_ROUTERLIST.apply(context, [
      {
        title,
        path,
        idList,
        id
      }
    ])
    goTop()
  }
})
const { routes } = router.options
router.beforeEach((to, from, next) => {
  // 这里主要是为了防止，用户已经进入了菜单列表，但是又刷新了页面，导致了vuex的数据重置，所以需要重新设置菜单和设置路由
  if (to.path.includes("menu") && !routes[2].children.length) {
    menu.mergeMenu().then(() => {
      // 404页面
      routes.push({
        path: "*",
        name: "error",
        component: () => import("@/views/error/error")
      })
      router.addRoutes(routes)
      next({ ...to, replace: true })
    })
  } else if (to.path === "/login" || from.path === "/login") {
    next()
  } else {
    next()
  }
});
export default router
